﻿
using JNPF.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PARK.Accessctl.Entitys;
using PARK.BussinCache.Entitys.Entity;
using PARK.BussinCache.Interfaces;
using PARK.CardAcct.Entitys;
using PARK.Consumer;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.TaskScheduler.Interfaces;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PARK.TaskScheduler
{
    /// <summary>
    /// 门禁权限任务队列
    /// </summary>
    [ApiDescriptionSettings(Tag = "AccCtlAuthJob", Name = "accCtlAuthJobtask", Order = 220)]
    [Route("api/[controller]")]
    public class AccCtlAuthJobService : BackgroundService, IAccCtlAuthJobService, IDynamicApiController, ITransient
    {
        private readonly SqlSugarScope _db;
        private readonly int _times = 0;
        private readonly IConsumRefundRepository _ConsumRefundRepository;
        private readonly IParkCacheRepository _parkCacheRepository;
        private readonly IUniubiSdkRepository _uniubiSdkRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="db"></param>
        /// <param name="consumRefundRepository"></param>
        /// <param name="parkCacheRepository"></param>
        /// <param name="uniubiSdkRepository"></param>
        public AccCtlAuthJobService(ILogger<RefundJobService> logger,
            ISqlSugarClient db,
            IConsumRefundRepository consumRefundRepository,
            IParkCacheRepository parkCacheRepository,
            IUniubiSdkRepository uniubiSdkRepository)
        {
            _db = (SqlSugarScope)db;
            _ConsumRefundRepository = consumRefundRepository;
            _parkCacheRepository = parkCacheRepository;
            _uniubiSdkRepository = uniubiSdkRepository;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

        }
        /// <summary>
        /// 启动自启动任务
        /// </summary>
        [NonAction]
        public async void StartTimerJob()
        {
            new LoggEx().Info("门禁权限处理->队列开始执行...");
            CancellationToken stoppingToken = new CancellationToken();
            while (!stoppingToken.IsCancellationRequested)
            {
                await new TaskFactory().StartNew(() =>
                {
                    try
                    {
                        RunAccAuthQueue();
                        //每晚1.10
                        if(DateTime.Now.Hour==1 && DateTime.Now.Millisecond == 10)
                        {
                            RunAccAuthDb();
                        }
                    }
                    catch (Exception e)
                    {
                        new LoggEx().Info("门禁权限处理,队列异常:=============失败=====" + e.Message);
                    }
                    //定时任务休眠
                    Thread.Sleep(500);
                });
            }
        }

        #region 处理门禁权限任务_队列
        /// <summary>
        /// 处理门禁权限任务_队列
        /// </summary>
        void RunAccAuthQueue()
        {
            try
            {
                var _AuthEntityJson = _parkCacheRepository.GetAccAuthqueueList();
                if (!string.IsNullOrEmpty(_AuthEntityJson))
                {
                    var queueItem = JsonConvert.DeserializeObject<List<AccessCtlauthTaskEntity>>(_AuthEntityJson);
                    foreach (var _AuthEntity in queueItem)
                    {
                        ExecauthTask(_AuthEntity);
                    }
                }
            }
            catch(Exception ex)
            {
                new LoggEx().errlog("处理门禁权限任务->RunAccAuthQueue(),异常:" + ex.Message);
            }
        }
        #endregion

        #region 处理门禁权限任务_取得数据库
        /// <summary>
        /// 处理门禁权限任务_取得数据库
        /// </summary>
        void RunAccAuthDb()
        {
            try
            {
                var _Tasklist = _db.Queryable<AccessCtlauthTaskEntity>().Where(t => t.DeleteMark == 0 && t.TaskStatus != 2).ToList();
                foreach (var _AuthEntity in _Tasklist)
                {
                    ExecauthTask(_AuthEntity);
                }
            }
            catch (Exception ex)
            {
                new LoggEx().errlog("处理门禁权限任务->RunAccAuthDb(),异常:" + ex.Message);
            }
        }
        #endregion

        #region 调用宇泛接口处理权限
        /// <summary>
        /// 调用宇泛接口处理权限
        /// </summary>
        /// <param name="_AuthEntity"></param>
        void ExecauthTask(AccessCtlauthTaskEntity _AuthEntity)
        {
            try
            {
                if (_AuthEntity != null)
                {
                    var _isSucc = 0;
                    var _strResult = "";
                    var Paras = new List<SugarParameter>();
                    var _deviceNo = _AuthEntity.CtlSn;
                    //获取当前用户
                    var _EyeEntity = _db.Queryable<EmployeeEntity>().First(p => p.EmployeeId == _AuthEntity.EmployeeId);
                    if (_EyeEntity == null) return;
                    var _admitGuid = _EyeEntity.uni_admitGuid;
                    if (_AuthEntity.AddorDel == 1)
                    {
                        //调用宇泛接口,新增权限
                        var _uniret = _uniubiSdkRepository.authdeviceAdd(_deviceNo, _admitGuid, _AuthEntity.CompanyId);
                        if (_uniret.result == 1)
                        {
                            //写入权限表
                            _isSucc = 1;
                            _strResult = _uniret.msg;
                        }
                    }
                    else if (_AuthEntity.AddorDel == 2)
                    {
                        //调用宇泛接口,移除权限
                        var _uniret = _uniubiSdkRepository.authdeviceDelete(_deviceNo, _admitGuid, _AuthEntity.CompanyId);
                        if (_uniret.result == 1)
                        {
                            //删除权限表
                            _isSucc = 1;
                            _strResult = _uniret.msg;
                        }
                    }
                    //更新解析状态
                    var Pars = new List<SugarParameter>(){
                                        new SugarParameter("@taskId",_AuthEntity.TaskId),
                                        new SugarParameter("@isSucc",_isSucc),
                                        new SugarParameter("@strResult",_strResult)
                                    };
                    _db.Ado.UseStoredProcedure().ExecuteCommand("P_ctlAuthTask_StatusUpdate", Pars);
                }
            }
            catch (Exception ex)
            {
                new LoggEx().errlog("处理门禁权限任务->ExecauthTask(),异常:" + ex.Message);
            }
        }
        #endregion
    }
}
